package org.tinygame.herostory.cmdHandle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinygame.herostory.async.AsyncOperationProcessor;
import org.tinygame.herostory.login.LoginService;
import org.tinygame.herostory.login.db.UserEntity;
import org.tinygame.herostory.model.User;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

import java.util.function.Function;


/**
 * 用户登录指令处理器
 */
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd>{
    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(UserLoginCmdHandler.class);
    /**
     * 处理指令
     *
     * @param ctx
     * @param cmd
     */
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {
        if (null == ctx || null == cmd) {
            return;
        }
        String userName = cmd.getUserName();
        String password = cmd.getPassword();

        LOGGER.info("userName = {},password = {}",userName,password);

        AsyncOperationProcessor.getInstance().process(()->{


            LoginService.getInstance().userLogin(userName,password,(userEntity) ->{
                if (null == userEntity){
                    LOGGER.error("用户登录失败，userName = {}",userName);
                    return null;
                }

                LOGGER.info("当前线程 = {}",Thread.currentThread().getName());

                LOGGER.info(
                        "用户登录成功, userId = {}, userName = {}",
                        userEntity.userId,
                        userEntity.userName
                );

                int userId = userEntity.userId;
                String heroAvatar = userEntity.heroAvatar;

                //新建用户
                User newUser = new User();
                newUser.userId = userId;
                newUser.userName = userEntity.userName;
                newUser.hereAvatar = heroAvatar;
                newUser.currHp = 100;
                //将用户加入管理器
                UserManager.addUser(newUser);

                //将用户ID加入到Channel中
                ctx.channel().attr(AttributeKey.valueOf("userId")).set(userId);

                GameMsgProtocol.UserLoginResult.Builder resultBuilder = GameMsgProtocol.UserLoginResult.newBuilder();
                resultBuilder.setUserId(newUser.userId);
                resultBuilder.setUserName(newUser.userName);
                resultBuilder.setHeroAvatar(newUser.hereAvatar);

                //构建结果并发送
                GameMsgProtocol.UserLoginResult newResult = resultBuilder.build();
                ctx.writeAndFlush(newResult);
                return null;
            });
        });
    }
}
